<template>
  <div class="lnventory">
    <div style="display: flex; justify-content: space-between">
      <div style="display: flex;">
        <el-button size="medium" type="primary" plain @click="add">
          新增产品
        </el-button>
        <div style="display: flex;margin-left: 20px; line-height: 40px;">
          <el-radio v-model="radio" :label="0" @input="radioChange">
            库存列表
          </el-radio>
          <el-radio v-model="radio" :label="1" @input="radioChange">
            计算成品
          </el-radio>
        </div>
      </div>
      <div style="display: flex;">
        <div v-if="radio === 1" style="display: flex;">
          <div style="line-height: 40px;">
            <el-radio v-model="devicesType" :label="0" @input="typeChange">
              成品列表
            </el-radio>
            <el-radio v-model="devicesType" :label="1" @input="typeChange">
              零件列表
            </el-radio>
          </div>
          <div style="margin-left: 20px;">
            <label>百分比：</label>
            <el-input v-model="bfbinpt" style="width: 70px" @change="updataPercent">
            </el-input>
            <el-button type="primary" style="margin-left: 10px;" @click="calculate" v-debounce>
              开始计算
            </el-button>
          </div>
        </div>
        <div v-if="radio === 0" style="display: flex">
          <el-input v-model="input" style="width: 250px; margin-left: 10px" placeholder="按产品名称,型号搜索"
            @change="getAllGoods">
          </el-input>
          <el-select v-model="warehouseType" @change="changeType" style="width: 120px; margin-left: 10px">
            <el-option label="全部" :value="void 0"></el-option>
            <el-option v-for="item in productlibraryList" :label="item.libraryName" :key="item.id"
              :value="item.id"></el-option>
          </el-select>
          <el-select v-model="receiptsStatusValue" @change="changeType" style="width: 120px; margin-left: 10px">
            <el-option label="全部" :value="void 0"></el-option>
            <el-option v-for="item in productTypeList" :label="item.productType" :key="item.id"
              :value="item.id"></el-option>
          </el-select>
          <el-button style="margin-left: 10px" @click="reset" v-debounce>
            重置
          </el-button>
        </div>
      </div>
    </div>

    <!-- 库存列表 -->
    <div class="goods-table" v-if="radio === 0">
      <el-table :data="tableData" v-loading="loading" border stripe style="width: 100%" height="100%"
        key="lnventoryTable" ref="multipleTable">
        <el-table-column prop="i" label="序号" fixed="left" width="40">
        </el-table-column>
        <el-table-column label="产品图片" width="115">
          <template slot-scope="scope">
            <el-image style="width: 90px; height: 90px" :src="READ_IMG_URL + scope.row.image"
              :preview-src-list="new Array(READ_IMG_URL + scope.row.image)" :fit="cover">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="warehouseType" label="类型库" width="180">
          <template slot-scope="scope">
            <div>{{ productlibraryList.find(item => item.id == scope.row.warehouseType)?.libraryName ?? "无类型库"
              }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="isProduct" label="类型" width="90">
          <template slot-scope="scope">
            <el-tag>{{ productTypeList.find(item => item.id == scope.row.isProduct)?.productType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="partName" label="产品名称" width="150">
        </el-table-column>
        <el-table-column prop="model" label="产品型号" width="200">
        </el-table-column>
        <el-table-column prop="count" label="库存" width="50">
        </el-table-column>
        <el-table-column prop="unit" label="计量单位" width="50">
          <template slot-scope="scope">
            <div v-if="scope.row.unit">{{ unitList.find(item => item.id == scope.row.unit)?.unitMeasure }}</div>
            <div v-else>{{ "个" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="cost" :label="costLabel()" width="80" v-if="userInfo.roleId === '1'">
        </el-table-column>
        <el-table-column prop="devicesDescribe" label="产品描述" width="200">
        </el-table-column>
        <el-table-column prop="supId" label="最后一次供货的供应商" width="200" v-if="userInfo.roleId == 1">
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="200">
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" :disabled="chengpnDisabled(scope.row)" @click="chengpn(scope.row)">
              成品管理
            </el-button>
            <el-button size="mini" v-show="root" @click="Employeeupda(scope.row.id)">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="deleteGoods(scope.row)" :disabled="userInfo.roleId !== '1'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage" :page-sizes="[20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 计算成品 -->
    <div class="goods-table" v-if="radio === 1">
      <el-table :data="devicesList" v-loading="loading" border stripe style="width: 100%" max-height="575"
        key="computeTable">
        <el-table-column prop="i" label="序号" fixed="left" width="60">
        </el-table-column>
        <el-table-column label="产品图片" width="120">
          <template slot-scope="item">
            <el-image style="width: 100px; height: 100px" :src="READ_IMG_URL + item.row.image"
              :preview-src-list="new Array(READ_IMG_URL + item.row.image)" :fit="cover">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="isProduct" label="产品类型" width="80">
          <template slot-scope="scope">
            <el-tag>{{ productTypeList.find(item => item.id == scope.row.isProduct)?.productType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="partName" label="产品名称" fit>
        </el-table-column>
        <el-table-column prop="model" label="产品型号" fit>
        </el-table-column>
        <el-table-column prop="devicesDescribe" label="产品描述" fit>
        </el-table-column>
        <el-table-column prop="count" label="库存数量" width="100">
        </el-table-column>
        <el-table-column prop="unit" label="计量单位" width="70">
          <template slot-scope="scope">
            <div v-if="scope.row.unit">{{ unitList.find(item => item.id == scope.row.unit)?.unitMeasure }}</div>
            <div v-else>{{ "个" }}</div>
          </template>
        </el-table-column>
        <el-table-column v-if="devicesType === 0" prop="countMax" key="countMax" label="最大组装数量" width="150">
        </el-table-column>
        <el-table-column v-if="devicesType === 0" label="零件列表" width="100" key="partList">
          <template slot-scope="scope">
            <el-button type="text" @click="partListShow(scope.row)">
              零件列表
            </el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="devicesType === 1" prop="expendTotal" key="expendTotal" label="总消耗数量" width="150">
        </el-table-column>
        <el-table-column v-if="devicesType === 1" prop="lackTotal" key="lackTotal" label="总缺少数量" width="150">
        </el-table-column>
      </el-table>

      <el-pagination background @size-change="calculateSizeChange" @current-change="calculateCurrentChange"
        :current-page="calculateCurrentPage" :page-sizes="[20, 50, 100]" :page-size="calculatePageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="calculateTotal">
      </el-pagination>
    </div>

    <!-- 组装成品 -->
    <el-dialog :visible.sync="assembleDialogoShow" width="75%" :title="deviceTitle" @close="assembleClose">
      <div>
        <div style="display: flex;justify-content: space-between;">
          <div>
            <el-radio v-model="manageType" :label="0">组装成品</el-radio>
            <el-radio v-model="manageType" :label="1">拆解成品</el-radio>
          </div>
          <div>
            <label>成品数量：</label>
            <el-input v-model="productCount" type="number" style="width: 150px;" @input="checkPartCount">
            </el-input>
          </div>
        </div>
        <el-table :data="selectDevices.productPartList" border stripe style="width: 100%;margin-top: 10px;"
          :max-height="400">
          <el-table-column prop="i" fixed="left" label="序号" width="60">
          </el-table-column>
          <el-table-column label="图片" width="120">
            <template slot-scope="scope">
              <el-image :src="READ_IMG_URL + scope.row.image" style="width: 90px; height: 90px;"
                :preview-src-list="new Array(READ_IMG_URL + scope.row.image)">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="partName" label="零件名称" fit>
          </el-table-column>
          <el-table-column prop="model" label="零件型号" fit>
          </el-table-column>
          <el-table-column prop="devicesDescribe" label="产品描述" fit>
          </el-table-column>
          <el-table-column prop="number" label="组装数量" width="100">
          </el-table-column>
          <el-table-column prop="number" label="计量单位" width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.unit">{{ unitList.find(item => item.id == scope.row.unit)?.unitMeasure }}</div>
              <div v-else>{{ "个" }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="库存数量" width="100">
          </el-table-column>
          <el-table-column prop="expend" label="消耗数量" width="100" v-if="manageType == 0">
          </el-table-column>
          <el-table-column prop="expend" label="拆解数量" width="100" v-if="manageType == 1">
          </el-table-column>
          <el-table-column prop="lack" label="缺少数量" width="100" v-if="manageType == 0">
            <template slot-scope="scope">
              <span v-if="scope.row.lack > 0" style="color: red;">
                {{ scope.row.lack }}
              </span>
              <span v-else>{{ scope.row.lack }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <el-button @click="assembleDialogoShow = false">取消</el-button>
        <el-button type="primary" @click="assemble" v-debounce v-if="manageType == 0">
          组装
        </el-button>
        <el-button type="primary" @click="dismantle" v-debounce v-if="manageType == 1">
          拆解
        </el-button>
      </div>
    </el-dialog>

    <!-- 零件列表 -->
    <el-dialog :visible.sync="partDialogoShow" width="75%" title="零件列表" @close="assembleClose">
      <div>
        <el-table :data="selectDevices.productPartList" border stripe style="width: 100%;margin-top: 10px;"
          :max-height="500">
          <el-table-column prop="i" fixed="left" label="序号" width="60">
          </el-table-column>
          <el-table-column label="图片" width="120">
            <template slot-scope="scope">
              <el-image :src="READ_IMG_URL + scope.row.image" style="width: 90px; height: 90px;"
                :preview-src-list="new Array(READ_IMG_URL + scope.row.image)">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="partName" label="零件名称" fit>
          </el-table-column>
          <el-table-column prop="model" label="零件型号" fit>
          </el-table-column>
          <el-table-column prop="number" label="计量单位" width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.unit">{{ unitList.find(item => item.id == scope.row.unit)?.unitMeasure }}</div>
              <div v-else>{{ "个" }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="number" label="组装数量" width="100">
          </el-table-column>
          <el-table-column prop="count" label="库存数量" width="100">
          </el-table-column>
          <el-table-column prop="expend" label="消耗数量" width="100">
          </el-table-column>
          <el-table-column prop="lack" label="缺少数量" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.lack > 0" style="color: red;">
                {{ scope.row.lack }}
              </span>
              <span v-else>{{ scope.row.lack }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import dayjs from "dayjs";
import {
  addEmployeeProfile,
  selectEmployeeProfileById,
  UploadFile,
  updateEmployeeProfile,
  apply, //新增产品
  suppliersList, //供应商列表
  suppliersAdd, //新增供应商
  purchaseList, //采购订单列表
  selectName, //查询产品名称
  purchaseReceiptsApply, //申请入库
  adminCheck, //审核入库
  purchaseReceiptsInfo, //通过id查询入库信息
  devicesSelectLike, //模糊查询仓库产品列表
  addProductPart, //添加产品零件
  addProductIs, //新增产品
  updatePercent, //修改百分比
  selectPercent, //查询百分比
  adminUpdateDevice, //修改产品
} from "../../../api/all";
import warehouseApi from "../../../api/warehouse";
import config from '../../../api/apiURL.js';
import unitMeasure from '../../../api/unitMeasure.js';
import productType from '../../../api/productType.js';
import productlibrary from '../../../api/productlibrary.js';
export default {
  computed: {
    ...mapGetters(['isProduct'])
  },
  data() {
    return {
      READ_IMG_URL: config.READ_IMG_URL,
      radio: 0,
      devicesType: 0,
      userInfo: {},
      bt1: false,
      role3: false,
      root: false,
      //数量状态
      smstatus: 0,
      //百分比
      bfbinpt: "80",
      //新增产品
      ProductsOne: {
        id: "",
        partName: "",
        model: "",
        price: "",
        remark: "",
        image: "",
        count: "",
        part: [],
      },
      //产品组装详细
      patIn: "",
      //临时零件id
      Itpartid: "",
      //临时数量
      Itnumber: "",
      //临时名称
      Itname: "",
      //产品添加零件对象
      partinfo: {
        productPartId: "",
        devicesId: "",
        part: [], //partId number partName
        model: "",
      },
      //零件组装数据
      partlist: "",
      tags: [
        { name: "外壳1个" },
        { name: "定子1个" },
        { name: "转子1个" },
        { name: "轴承4个" },
        { name: "密封圈2个" },
      ],
      receiptsStatusValue: void 0,
      warehouseType: void 0,
      //采购订单列表
      options3: [
        { value: "选项1", label: "黄金糕" },
        { value: "选项2", label: "双皮奶" },
        { value: "选项3", label: "蚵仔煎" },
        { value: "选项4", label: "龙须面" },
        { value: "选项5", label: "北京烤鸭" },
      ],
      value3: "",
      loading2: false,
      value2: "",
      //搜索框的值
      input: "",
      // 图片预览
      srcList: [],
      srcList2: [],
      //修改按钮状态
      applyButton: 0, //0是新增 1是修改，2是申请修改
      // 上传图片文件
      selectedFile: null,
      //判断用户点击的是合同还是保密协议
      htdz: "",
      // 合同地址
      imageUrl: "",
      // 保密协议地址
      imageUrl2: "",
      //新增标题
      title: "新增产品",
      roleType: false,
      cover: "cover",
      // 显示表单
      addFromDialog: false,
      addFromDialog2: false,
      addFromDialog3: false,
      addFromDialog4: false,
      addFromDialog5: false,
      addFromDialogo6: false,
      addFromDialogo10: false,

      // 表格加载
      loading: false,
      //合同到期提醒
      dialogImageUrl: "",
      dialogVisible: false,
      //新增采购表格数据
      prudproducts: {
        suppliersId: "", //供应商id
        productsId: "", //产品id
        productsName: "", //产品名称
        description: "", //产品描述
        price: "", //产品价格
        model: "", //产品型号
        isIncludingTax: "", //是否含税
        number: "", //产品数量
        image: "", //产品图片
        purchaser: "", //采购人
        storageTime: "", //入库时间
        paymentType: "", //结款方式 (1现金,2月结)
        status: "", //入库状态 （0已通过，1待审核,2审核失败）
      },
      //采购入库信息
      PurchaseReceipts: {
        productsName: "", //产品名称
        purchaseOrdersId: "", //采购订单ID
        model: "", //产品型号
        price: "", //产品价格
        number: "", //产品数量
        isIncludingTax: "", //是否含税
        storageTime: "", //入库时间
        description: "", //产品描述
        image: "", //产品图片
        receiptsId: "", //入库id
        warehouseDevId: "", //仓库id
      },
      //表格数据
      tableData: [],
      //总数页
      total: 1,
      // 分页大小
      pageSize: 50,
      //记录当前页数
      currentPage: 1,
      //审核通过状态
      applyStatus: false,
      //是否含税
      SexCategory: [
        { label: "是", value: 0 },
        { label: "否", value: 1 },
      ],
      SexCategory2: [
        { label: "现金全款", value: 0 },
        { label: "分期付款 3期", value: 3 },
        { label: "分期付款 6期", value: 6 },
        { label: "分期付款 9期", value: 9 },
        { label: "分期付款 12期", value: 12 },
      ],
      SexCategory3: [],
      deviceTitle: "成品管理",
      manageType: 0,
      assembleDialogoShow: false,
      selectDevices: {
        productPartList: [],
        count: null
      },
      productCount: 1,
      devicesMap: {
        devicesVoList: [],
        devicesPartVoList: []
      },
      devicesList: [],
      partDialogoShow: false,
      calculateCurrentPage: 1,
      calculatePageSize: 50,
      calculateTotal: 0,
      unitList: new Array(),
      productTypeList: new Array(),
      productlibraryList: new Array()
    };
  },
  mounted() {
    let role = localStorage.getItem("role");
    if (role == 1 || role == 5) {
      this.role3 = true;
    }
    if (role == 1 || role == 4) {
      this.root = true;
    }
    let kes = window.sessionStorage.getItem("loginUser");
    let userObject = JSON.parse(kes);
    this.userInfo = userObject;
    if (userObject.roleType == "root") {
      this.roleType = true;
    }
    this.currentPage = this.$store.getters.purchase?.currentPage ?? 1
    this.pageSize = this.$store.getters.purchase?.pageSize ?? 50
    this.getAllGoods();
    //查询百分比
    selectPercent().then((data) => {
      this.bfbinpt = data.data;
    });
    // console.log("初始化时间:", dayjs())
    this.getUnit()
    this.getProductTypeList()
    this.getProductlibraryList()
  },
  //超级管理员显示功能
  methods: {
    // 格式化时间
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, "0");
      const day = d.getDate().toString().padStart(2, "0");
      const hours = d.getHours().toString().padStart(2, "0");
      const minutes = d.getMinutes().toString().padStart(2, "0");
      const seconds = d.getSeconds().toString().padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      // return `${year}-${month}-${day}`;
    },
    startTimeChange(value) {
      this.addEmployeeForm.startTime = dayjs(value).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      console.log("上架时间", dayjs(value).format("YYYY-MM-DD HH:mm:ss"));
    },
    endTimeChange(value) {
      this.addEmployeeForm.endTime = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
      console.log("上架时间", dayjs(value).format("YYYY-MM-DD HH:mm:ss"));
    },
    ModifyNumber(i) {
      this.Itnumber = this.partinfo.part[i].number;
      this.Itpartid = this.partinfo.part[i].partId;
      this.Itname = this.partinfo.part[i].partName;
      this.addFromDialogo6 = true;
    },
    addpart(id, name) {
      this.Itnumber = "";
      this.Itpartid = id;
      this.Itname = name;
      this.addFromDialogo6 = true;
    },
    addpart2(id, name) {
      this.Itnumber = "";
      this.Itpartid = id;
      this.Itname = name;
      this.addFromDialogo10 = true;
    },

    //检测最大组装数是否为null
    checkMaxCont(kes) {
      if (kes == null) {
        return "零件没有组装数量";
      }
      return kes;
    },

    //修改百分比
    updataPercent() {
      if (this.bfbinpt == "" || this.bfbinpt == null) {
        return;
      }
      updatePercent(this.bfbinpt).then(() => {
        // if (data.code == 200) {
        //   this.$message({
        //     type: "success",
        //     message: data.message,
        //   });
        // } else {
        //   this.$message({
        //     type: "error",
        //     message: data.message,
        //   });
        // }
      });
    },
    //检测最组装价格是否为null
    checkMaxPrice(kes) {
      if (kes == null) {
        return "零件没有组装价格";
      }
      return kes;
    },
    //成品组装
    chengpn(row) {
      this.deviceTitle = `成品管理 [ ${row.partName} ]`
      const data = {
        id: row.id
      }
      warehouseApi.getDevice(data).then(res => {
        if (res.code === 200) {
          this.selectDevices = res.data
          if (this.selectDevices.isProduct !== 1) {
            this.selectDevices.productPartList = res.data.productPartVoList.map(
              (item, index) => {
                item.i = index + 1;
                this.$set(item, 'expend', 0);
                this.$set(item, 'lack', 0);
                return item;
              }
            )
          }
          this.calculatedQuantity();
          this.assembleDialogoShow = true;
        }
      })
    },
    //提交添加零件
    addpartTs() {
      //创建一个对象
      let prt = {
        partId: this.Itpartid,
        number: this.Itnumber,
        partName: this.Itname,
      };
      //添加之前先检测数组中是否有该partid,如果有直接覆盖number
      let ishave = false;
      for (let i = 0; i < this.partinfo.part.length; i++) {
        if (this.partinfo.part[i].partId == prt.partId) {
          this.partinfo.part[i].number = prt.number;
          if (prt.partName.charAt(prt.partName.length - 1) != "个") {
            this.partinfo.part[i].partName = prt.partName + prt.number + "个";
          } else {
            // 使用正则表达式匹配数字并替换为空字符串
            let result = prt.partName.replace(/\d/g, "");
            //然后再去掉最后一个字符
            result = result.substring(0, result.length - 1);
            this.partinfo.part[i].partName = result + prt.number + "个";
          }
          ishave = true;
        }
      }
      if (ishave == true) {
        this.addFromDialogo6 = false;
        return;
      }

      //添加到数组中
      console.log("添加零件", this.partinfo);
      this.partinfo.part.push(prt);
      this.addFromDialogo6 = false;
    },

    //提交添加零件
    addpartTs2() {
      //创建一个对象
      let prt = {
        partId: this.Itpartid,
        number: this.Itnumber,
        partName: this.Itname,
      };
      //添加之前先检测数组中是否有该partid,如果有直接覆盖number
      let ishave = false;
      for (let i = 0; i < this.ProductsOne.part.length; i++) {
        if (this.ProductsOne.part[i].partId == prt.partId) {
          this.ProductsOne.part[i].number = prt.number;
          if (prt.partName.charAt(prt.partName.length - 1) != "个") {
            this.ProductsOne.part[i].partName =
              prt.partName + prt.number + "个";
          } else {
            // 使用正则表达式匹配数字并替换为空字符串
            let result = prt.partName.replace(/\d/g, "");
            //然后再去掉最后一个字符
            result = result.substring(0, result.length - 1);
            this.ProductsOne.part[i].partName = result + prt.number + "个";
          }
          ishave = true;
        }
      }
      if (ishave == true) {
        this.addFromDialogo6 = false;
        return;
      }

      //添加到数组中
      console.log("添加零件", this.ProductsOne);
      this.ProductsOne.part.push(prt);
      this.addFromDialogo6 = false;
    },

    //添加零件
    addProductList() {
      addProductPart(this.partinfo).then((data) => {
        if (data.code == 200) {
          this.$message({
            type: "success",
            message: data.message,
          });
          this.addFromDialog5 = false;
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },
    //删除标签元素
    handleClose(init) {
      this.partinfo.part.splice(this.partinfo.part.indexOf(init), 1);
    },
    //新增供应商
    addSupplierInfo() {
      suppliersAdd(this.suppliers).then((data) => {
        console.log("data", data.data);
        if (data.code == 200) {
          this.$message({
            type: "success",
            message: data.message,
          });
          this.addFromDialog3 = false;
          //再次查询供应商列表
          suppliersList().then((data) => {
            this.SexCategory3 = data.data;
          });
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },
    //入库状态方法
    receiptsStatus(i) {
      let val = "";
      if (i == 0) {
        val = "已入库";
      } else if (i == 1) {
        val = "待审核";
      } else if (i == 2) {
        val = "入库失败";
      } else if (i == 3) {
        val = "待财务审核";
      }
      return val;
    },

    //修改产品
    updatestay() {
      adminUpdateDevice(this.ProductsOne).then((data) => {
        if (data.code == 200) {
          this.$message({
            type: "success",
            message: "修改成功",
          });
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: "修改失败",
          });
        }
      });
    },
    // 新增产品
    submitaddEmployeeForm() {
      let val = this.infoPet();
      if (val == false) {
        return;
      }
      addEmployeeProfile(this.addEmployeeForm).then((data) => {
        if (data.code) {
          this.$message({
            type: "success",
            message: "新增成功",
          });
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: "新增失败",
          });
        }
      });
      this.addFromDialog = false;
    },
    //校验新增修改申请时的数据
    infoPet() {
      this.prudproducts.status = 1;
      //校验入库表格不能为空
      if (false) {
        // this.$message({
        //   type: "error",
        //   message: "请填写完整信息",
        // });
      } else {
        //添加入库申请
        apply(this.prudproducts).then((data) => {
          if (data.code) {
            this.$message({
              type: "success",
              message: "入库申请成功",
            });
            this.getAllGoods();
          } else {
            this.$message({
              type: "error",
              message: "入库申请失败",
            });
          }
        });
        return true;
      }
    },
    //新增产品
    addProductInt() {
      addProductIs(this.ProductsOne).then((data) => {
        if (data.code == 200) {
          this.$message({
            type: "success",
            message: data.message,
          });
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },
    //修改档案信息
    UpdateEmployee(i) {
      if (i == 2) {
        this.infoPet();
        return;
      }
      if (i == 3) {
        //申请入库
        this.PurchaseReceipts.purchaseOrdersId = this.value3;
        purchaseReceiptsApply(this.PurchaseReceipts).then((data) => {
          if (data.code == 200) {
            this.$message({
              type: "success",
              message: data.message,
            });
            this.getAllGoods();
          } else {
            this.$message({
              type: "error",
              message: data.message,
            });
          }
        });
        return;
      }
      updateEmployeeProfile(this.addEmployeeForm).then((data) => {
        if (data.code) {
          this.$message({
            type: "success",
            message: data.data,
          });
          this.getAllGoods();
          this.addFromDialog = false;
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },
    receiptsStatusSelect() {
      this.getAllGoods();
    },
    //输入框值发生变化
    inputName() {
      selectName(this.PurchaseReceipts.productsName).then((data) => {
        this.options2 = data.data;
        if (data.data.length == 0) {
          this.loading2 = false;
        } else {
          this.loading2 = true;
        }
      });
    },
    setName(i) {
      this.PurchaseReceipts.productsName = this.options2[i].partName;
      this.PurchaseReceipts.model = this.options2[i].model;
      this.PurchaseReceipts.number = this.options2[i].count;
      this.PurchaseReceipts.price = this.options2[i].price;
      this.PurchaseReceipts.description = this.options2[i].remark;
      this.PurchaseReceipts.isIncludeTax = this.options2[i].isIncludeTax;
      this.PurchaseReceipts.image = this.options2[i].image;
      this.PurchaseReceipts.isProduct = this.options2[i].isProduct;
      this.PurchaseReceipts.warehouseDevId = this.options2[i].id;

      this.loading2 = false;
    },
    //模糊查询信息
    likeEmployee() {
      devicesSelectLike(this.input).then((data) => {
        if (data.code) {
          this.total = data.data.total;
          this.tableData = data.data.devicesVoList.map((item, index) => {
            item.i = (this.currentPage - 1) * this.pageSize + index + 1;
            return item;
          });
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },
    //性别显示
    employeeSex(i) {
      let val = "";
      if (i == 0) {
        val = "男";
      }
      if (i == 1) {
        val = "女";
      }
      return val;
    },
    //添加供应商
    addSupplier() {
      this.addFromDialog3 = true;
    },
    //审核档案信息
    applyUpdateEmployee(id) {
      this.imgstatus();
      let kes = window.sessionStorage.getItem("loginUser");
      let userObject = JSON.parse(kes);
      //判断是否为超级管理  0是新增 1是修改，2是申请修改
      if (userObject.roleType == "root") {
        this.applyButton = 3;
      } else {
        this.applyButton = 2;
      }
      selectEmployeeProfileById(id).then((data) => {
        this.addEmployeeForm = data.data;
        this.imageUrl = data.data.employeeContractFile;
        this.imageUrl2 = data.data.employeeSecrecyFile;
        this.title = "编辑档案信息";
        this.getAllGoods();
        this.addFromDialog = true;
      });
    },
    //编辑档案信息
    Employeeupda(id) {
      this.$store.commit("SET_PURCHASE", {
        input: this.input,
        receiptsStatusValue: this.receiptsStatusValue,
        warehouseType: this.warehouseType,
        tableScoll: this.$refs.multipleTable.bodyWrapper.scrollTop,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
      localStorage.setItem("devicesId", id)
      this.$router.push({
        path: "/warehouse/lnventory/addLnventory"
      })
    },
    //上传图片
    selectFile(i) {
      this.htdz = i;
      this.$refs.fileInput.click();
    },
    //上传oss
    handleFileChange(event) {
      this.selectedFile = event.target.files[0];
      this.imageUrl = URL.createObjectURL(this.selectedFile);
      this.ProductsOne.image = this.imageUrl;
      this.uploadImage();
    },
    //初始化图片
    imgstatus() {
      let url =
        "https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png";
      this.imageUrl = url;
      this.imageUrl2 = url;
    },
    //发送上传文件api
    uploadImage() {
      let formData = new FormData();
      formData.append("file", this.selectedFile);
      UploadFile(formData).then((data) => {
        let url = data.data;
        if (this.htdz == 1) {
          this.addEmployeeForm.employeeContractFile = url;
        }
        if (this.htdz == 2) {
          this.addEmployeeForm.employeeSecrecyFile = url;
        }
      });
    },

    //入库审核信息展示id
    InventoryDetails(id) {
      console.log("id", id);
      purchaseReceiptsInfo(id).then((data) => {
        this.prudproducts = data.data;
        this.prudproducts.suppliersId = data.data.suppliersName;
        this.imageUrl = data.data.image;
      });
      this.addFromDialog = true;
    },
    //examineWarehousing 审核入库
    examineWarehousing(status) {
      adminCheck(this.prudproducts.receiptsId, status).then((data) => {
        if (data.code) {
          this.$message({
            type: "success",
            message: data.message,
          });
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },
    //申请入库
    caigoAdd() {
      this.addFromDialog4 = true;
      purchaseList().then((data) => {
        console.log("data", data.data);
        this.options3 = data.data;
      });
    },
    // 新增成品
    add() {
      this.$router.push({
        path: "/warehouse/lnventory/addLnventory"
      })
      // selectPartList().then((data) => {
      //   this.partlist = data.data;
      //   console.log("partlist", this.partlist);
      // });
      // this.bt1 = true;
      // this.title = "新增产品";
      // this.addFromDialog = true;
      // this.smstatus = 0;
      // this.getGoodsCategory();
    },
    changeType(e) {
      this.$store.commit('SET_PRODUCT', e);
      this.getAllGoods();
    },
    // 查询列表
    getAllGoods() {
      this.loading = true;
      const data = {
        partName: this.input ?? this.$store.getters.purchase?.input,
        isProduct: this.receiptsStatusValue ?? this.$store.getters.purchase?.receiptsStatusValue,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        warehouseType: this.warehouseType ?? this.$store.getters.purchase?.warehouseType,
      }
      warehouseApi.getDeviceList(data).then(res => {
        if (res.code === 200) {
          this.total = res.data.total
          this.tableData = res.data.devicesList.map((item, index) => {
            item.i = (this.currentPage - 1) * this.pageSize + index + 1;
            return item;
          })
        }
        this.$nextTick(() => {
          this.$refs.multipleTable.bodyWrapper.scrollTop = this.$store.getters.purchase?.tableScoll;
        })
      }).finally(() => {
        this.loading = false;
      })
      //   devicesSelectList(
      //     this.currentPage,
      //     this.pageSize,
      //     this.receiptsStatusValue
      //   ).then((res) => {
      //     if (res.code) {
      //       this.total = res.data.total;
      //       this.tableData = res.data.devicesInfoVoList.map((item,index) =>{
      //  item.i = (this.currentPage - 1) * this.pageSize + index + 1;
      //  return item;
      // });
      //       this.loading = false;
      //     } else {
      //       this.$message("列表加载错误");
      //     }
      //     console.log("获取商品列表");
      //   });
    },
    // pageSize变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getAllGoods();
    },
    // 页码变化
    handleCurrentChange(curPage) {
      this.currentPage = curPage;
      this.getAllGoods();
    },

    //采购订单状态
    orderStatus(i) {
      let val = "";
      if (i == 0) {
        val = "已通过";
      } else if (i == 1) {
        val = "待审核";
      } else if (i == 2) {
        val = "审核失败";
      }
      return val;
    },
    // 删除商品
    deleteGoods(row) {
      this.$confirm(
        `确定要删除产品《${row.partName}》吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        const data = {
          id: row.id
        }
        warehouseApi.deleteDevice(data).then(res => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getAllGoods();
          }
        })
      })
    },
    // 重置查询条件
    reset() {
      this.input = null;
      this.receiptsStatusValue = void 0
      this.warehouseType = void 0
      this.currentPage = 1;
      this.getAllGoods()
    },
    // 检查输入的成品数量
    checkPartCount() {
      let inputNumber = parseFloat(this.productCount);
      // 小于0
      if (inputNumber < 0.00) {
        inputNumber = 0;
      }
      // 使用正则表达式匹配小数点后两位以内的数字或整数
      // let regex = /^\d+(\.\d{1,2})?$/;
      // if (!regex.test(inputNumber)) {
      //   inputNumber = 1
      // }
      this.productCount = inputNumber;
      this.calculatedQuantity();
    },
    // 计算零件组装数量
    calculatedQuantity() {
      //console.log("=====>",this.selectDevices.productPartList)
      if (this.selectDevices.productPartList.length > 0) {
        this.selectDevices.productPartList.forEach(item => {
          item.expend = item.number * this.productCount;
          let surplus = item.count - item.expend;
          item.lack = 0;
          if (surplus < 0) {
            item.lack = surplus * (-1)
          }
        })
      }
    },
    // 成品管理按钮是否禁用
    chengpnDisabled(row) {
      if (this.userInfo.roleId === '1' && row.isProduct !== 1) {
        return false;
      } else if (this.userInfo.roleId === '4' && row.isProduct !== 1) {
        return false;
      } else if (this.userInfo.roleId === '5' && row.isProduct !== 1) {
        return false;
      }
      return true;
    },
    // 关闭组装
    assembleClose() {
      this.selectDevices = {
        productPartList: [],
        count: null
      }
      this.productCount = 1;
      this.manageType = 0;
    },
    // 确定组装成品
    assemble() {
      // 判断是否缺少零件
      if (this.selectDevices.productPartList.length > 0) {
        if (this.selectDevices.productPartList.some(item => item.lack > 0)) {
          this.$message.error("零件库存不足，无法组装");
          return;
        }
      }
      let msg = `确定要组装${this.productCount}个[${this.selectDevices.partName}]吗？`
      this.$confirm(msg, "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          id: this.selectDevices.id,
          productCount: this.productCount,
        }
        warehouseApi.assembleDevice(data).then(res => {
          if (res.code === 200) {
            this.$message.success("组装成功")
            this.getAllGoods();
          }
        }).finally(() => {
          this.assembleDialogoShow = false
        })
      })
    },
    // 拆解成品
    dismantle() {
      // 判断成品数量
      if (this.selectDevices.count < this.productCount) {
        this.$message.error("成品库存不足，无法拆解");
        return;
      }
      let msg = `确定要拆解${this.productCount}个[${this.selectDevices.partName}]吗？`
      this.$confirm(msg, "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          id: this.selectDevices.id,
          productCount: this.productCount,
        }
        warehouseApi.dismantleDevice(data).then(res => {
          if (res.code === 200) {
            this.$message.success("拆解成功")
            this.getAllGoods();
            this.assembleDialogoShow = false
          }
        })
      })
    },
    // 计算成品
    calculate() {
      const loading = this.$loading({
        lock: true,
        text: '计算中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      warehouseApi.calculateAssembleDevice().then(res => {
        if (res.code === 200) {
          this.devicesMap = res.data;
          this.getDevicesList();
        }
      }).finally(() => {
        loading.close();
      })
    },
    // 获取产品列表
    getDevicesList() {
      this.loading = true;
      this.devicesList = [];
      // 起始位置，（currentPage-1）* pageSize
      let offset = (this.calculateCurrentPage - 1) * this.calculatePageSize;
      // 结束位置，currentPage * pageSize
      let result = this.calculateCurrentPage * this.calculatePageSize;
      if (this.devicesType === 0) {
        let devicesVoList = this.devicesMap.devicesVoList;
        this.calculateTotal = devicesVoList.length;
        // 判断结束位置是否大于总条数
        let endset = this.calculateTotal;
        if (result < this.calculateTotal) {
          // 小于
          let endset = result;
        }
        for (var i = offset; i < endset; i++) {
          this.devicesList.push(devicesVoList[i]);
        }
        this.devicesList.forEach((item, index) => {
          item.i = offset + index + 1;
        })
      } else {
        let devicesPartVoList = this.devicesMap.devicesPartVoList;
        this.calculateTotal = devicesPartVoList.length;
        // 判断结束位置是否大于总条数
        let endset = this.calculateTotal;
        if (result < this.calculateTotal) {
          // 小于
          let endset = result;
        }
        for (let i = offset; i < endset; i++) {
          this.devicesList.push(devicesPartVoList[i]);
        }
        this.devicesList.forEach((item, index) => {
          item.i = offset + index + 1;
        })
      }
      this.loading = false;
    },
    // 选项改变
    radioChange() {
    },
    // 类型改变
    typeChange() {
      this.calculateCurrentPage = 1;
      this.calculatePageSize = 50;
      this.calculateTotal = 0;
      this.getDevicesList();
    },
    // 打开零件列表
    partListShow(row) {
      this.partDialogoShow = true;
      this.selectDevices = row;
      this.selectDevices.productPartList = row.productPartVoList.map((item, index) => {
        item.i = index + 1;
        return item;
      })
    },
    // 计算成品pageSize变化
    calculateSizeChange(pageSize) {
      // console.log("pageSize===>",pageSize)
      this.calculatePageSize = pageSize;
      this.getDevicesList();
    },
    calculateCurrentChange(currentPage) {
      // console.log("currentPage===>",currentPage)
      this.calculateCurrentPage = currentPage;
      this.getDevicesList();
    },
    costLabel() {
      if (this.receiptsStatusValue == 0) {
        return "成本费";
      }
      return "采购单价";
    },
    getUnit() {
      unitMeasure.getUnitMeasure().then(res => {
        this.unitList = res.data
      })
    },
    getProductTypeList() {
      productType.getProductType().then(res => {
        this.productTypeList = res.data
      })
    },
    getProductlibraryList() {
      productlibrary.getProductlibrary().then(res => {
        this.productlibraryList = res.data
      })
    }
  },
};
</script>

<style scoped>
.page {
  text-align: center;
}

.nameBox {
  overflow: auto;
  /* 显示滚动条 */
  z-index: 99;
  margin-top: 5px;
  font-size: 12px;
  text-align: center;
  width: 205px;
  height: 170px;
  border-radius: 5px;
  background-color: #ffffff;
  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.2);
  position: absolute;
}

.lnventory {
  height: 100%;
}

.goods-table {
  height: 94%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  margin-top: 10px;
}

.imgUrl {
  width: 100px;
  height: 100px;
  object-fit: cover;
  /* 保持原始宽高比，填充容器 */
}

.htimg {
  width: 150px;
  height: 150px;
  object-fit: cover;
  /* 保持原始宽高比，填充容器 */
}
</style>
